package cn.th.service.impl;

import cn.th.dto.AdDto;
import cn.th.dto.UserDto;
import cn.th.entity.*;
import cn.th.mapper.UserGiftMapper;
import cn.th.mapper.UserMapper;
import cn.th.mapper.UserTaskMapper;
import cn.th.service.IUserGiftService;
import cn.th.service.IUserService;
import cn.th.service.IUserTaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author cn.th
 * @since 2024-03-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserGiftService userGiftService;

    @Autowired
    private IUserTaskService userTaskService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserGiftMapper userGiftMapper;

    @Autowired
    private UserTaskMapper userTaskMapper;
    /**
     * 查找用户
     * @param page
     * @param limit
     * @param school 所在学校
     * @param name 该生姓名，不支持模糊查询
     * @param sex 性别
     * @param myClass 班级
     * @param sno 学号
     * @param location 家乡
     * @param major 专业
     * @param academy 学院
     * @param dormitory 宿舍楼
     * @param dormitoryNumber 宿舍号
     * @param state 状态
     * @return
     */
    @Override
    public Map<String, Object> queryUser(int page, int limit, String school, String name, String sex, String myClass, String sno, String location, String major, String academy, String dormitory, String dormitoryNumber, String state) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(StringUtils.hasLength(school), User::getSchool, school);
        wrapper.eq(StringUtils.hasLength(name), User::getName, name);
        wrapper.eq(StringUtils.hasLength(sex), User::getSex, sex);
        wrapper.eq(StringUtils.hasLength(myClass), User::getMyclass, myClass);
        wrapper.eq(StringUtils.hasLength(sno), User::getSno, sno);
        wrapper.eq(StringUtils.hasLength(location), User::getLocation, location);
        wrapper.eq(StringUtils.hasLength(major), User::getMajor, major);
        wrapper.eq(StringUtils.hasLength(academy), User::getAcademy, academy);
        wrapper.eq(StringUtils.hasLength(dormitory), User::getDormitory, dormitory);
        wrapper.eq(StringUtils.hasLength(dormitoryNumber), User::getDormitoryNumber, dormitoryNumber);
        wrapper.eq(StringUtils.hasLength(state), User::getState, state);

        Page<User> page1 = new Page<>(page,limit);
        Page<UserDto> userDtoPage = new Page<>();

        userService.page(page1,wrapper);

        //对象拷贝
        BeanUtils.copyProperties(page1,userDtoPage,"records");

        List<User> records = page1.getRecords();

        List<UserDto> list = records.stream().map((item) -> {
            UserDto userDto = new UserDto();

            BeanUtils.copyProperties(item,userDto);

            //当前广告的id
            Long userId = item.getId();//用户id

            //查找用户所兑换的礼品
            LambdaQueryWrapper<UserGift> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserGift::getUserId,userId);

            //将用户兑换的所有礼品存入userGiftList中
            List<UserGift> userGiftList = userGiftService.list(lambdaQueryWrapper);

            //将用户兑换的礼品保存到UserDto中
            userDto.setUserGiftList(userGiftList);


            //查找用户所接取的任务
            LambdaQueryWrapper<UserTask> lambdaQueryWrapperTask = new LambdaQueryWrapper<>();
            lambdaQueryWrapperTask.eq(UserTask::getUserId,userId);

            //将用户接取的所有任务存入userTaskList中
            List<UserTask> userTaskList = userTaskService.list(lambdaQueryWrapperTask);

            //将用户接取的任务保存到UserDto中
            userDto.setUserTasks(userTaskList);

            //返回userDto
            return userDto;
        }).collect(Collectors.toList());

        userDtoPage.setRecords(list);

        Map<String, Object> data = new HashMap<>();
        data.put("total",userDtoPage.getTotal());
        data.put("rows",userDtoPage.getRecords());

        return data;
    }

    /**
     * 新增用户
     * @param file
     * @return
     */
    @Transactional
    public ResponseEntity<String> saveFile(MultipartFile file) {
        try {
            // 读取Excel文件
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历Excel表格数据,从第二行开始读
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                Row row = sheet.getRow(i);

                String school = row.getCell(0).getStringCellValue(); // 学校
                String name = row.getCell(1).getStringCellValue(); // 姓名

                DecimalFormat df = new DecimalFormat("#");
                Integer sex = (int) row.getCell(2).getNumericCellValue(); //性别

                String myClass = row.getCell(3).getStringCellValue(); // 班级

                double cellValueSno = row.getCell(4).getNumericCellValue();
                String sno = df.format(cellValueSno); // 学号

                String location = row.getCell(5).getStringCellValue(); // 家乡所在地

                double cellValueNumber = row.getCell(6).getNumericCellValue();
                String number = df.format(cellValueNumber); // 电话号码

                String major = row.getCell(7).getStringCellValue(); // 专业
                String academy = row.getCell(8).getStringCellValue(); // 学院
                String dormitory = row.getCell(9).getStringCellValue(); // 宿舍楼

                double cellValueAdmissionNumber = row.getCell(10).getNumericCellValue();
                String admissionNumber = df.format(cellValueAdmissionNumber); // 录取通知书编号

//                double cellValueIdNumber = row.getCell(11).getNumericCellValue();
//                String idNumber = df.format(cellValueIdNumber); // 身份证号码
                String idNumber = row.getCell(11).getStringCellValue(); // 宿舍楼

                double cellValueDormitoryNumber = row.getCell(12).getNumericCellValue();
                String dormitoryNumber = df.format(cellValueDormitoryNumber); // 宿舍号

//                Integer sex = (int) row.getCell(3).getNumericCellValue(); // 获取每行的第四个单元格中的内容

                // 进行操作，对new出来的Dormitory进行赋值
                User user = new User();
                user.setSchool(school);
                user.setName(name);
                user.setSex(sex);
                user.setMyclass(myClass);
                user.setSno(sno);
                user.setLocation(location);
                user.setPhone(number);
                user.setMajor(major);
                user.setAcademy(academy);
                user.setDormitory(dormitory);
                user.setAdmissionNumber(admissionNumber);
                user.setIdNumber(idNumber);
                user.setDormitoryNumber(dormitoryNumber);

                // 将数据存入数据库
                userService.save(user);
            }
            return ResponseEntity.ok("Excel上传成功");
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Excel上传失败");
        }
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @Transactional
    public void deleteById(String ids) {
        userMapper.deleteBatchByIds(ids);

        //删除用户-物品表中的数据----user_gift
        userGiftMapper.deleteBatchByIds(ids);

        //删除用户-任务表中的数据----user_task
        userTaskMapper.deleteBatchByIds(ids);
    }

    /**
     * 修改用户信息
     * @param userDto
     * @return
     */
    @Transactional
    public void updateWithId(UserDto userDto) {
        //更新用户表基本信息
        this.updateById(userDto);

        //清理当前用户对应的礼物表---user_gift表的delete操作
        LambdaQueryWrapper<UserGift> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(UserGift::getUserId,userDto.getId());
        userGiftService.remove(queryWrapper);

        //添加当前提交过来的礼物数据---user_gift表的insert操作
        List<UserGift> userGiftList = userDto.getUserGiftList();

        userGiftList = userGiftList.stream().map((item) -> {
            item.setUserId(userDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存数据到user_gift表中
        userGiftService.saveBatch(userGiftList);


        //清理当前用户对应的任务表---user_task表的delete操作
        LambdaQueryWrapper<UserTask> queryWrapperUserGift = new LambdaQueryWrapper();
        queryWrapperUserGift.eq(UserTask::getUserId,userDto.getId());
        userTaskService.remove(queryWrapperUserGift);

        //添加当前提交过来的任务数据---user_task表的insert操作
        List<UserTask> userTaskList = userDto.getUserTasks();

        userTaskList = userTaskList.stream().map((item) -> {
            item.setUserId(userDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存数据到user_gift表中
        userTaskService.saveBatch(userTaskList);
    }

    /**
     * 修改用户时页面的数据展示
     * @param id
     * @return
     */
    @Transactional
    @Override
    public UserDto getUserDtoById(Long id) {
        //查询用户基本信息，从user表查询
        User user = this.getById(id);

        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user,userDto);

        //查询当前用户对应的礼物信息，从user_gift表查询
        LambdaQueryWrapper<UserGift> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserGift::getUserId,user.getId());
        List<UserGift> userGiftList = userGiftService.list(queryWrapper);
        userDto.setUserGiftList(userGiftList);

        //查询当前用户对应的任务信息，从user_task表查询
        LambdaQueryWrapper<UserTask> queryWrapperTask = new LambdaQueryWrapper<>();
        queryWrapperTask.eq(UserTask::getUserId,user.getId());
        List<UserTask> userTaskList = userTaskService.list(queryWrapperTask);
        userDto.setUserTasks(userTaskList);

        return userDto;
    }
}
